#include "xxx_dev.h"
#include "xxx_info.h"
#include "xxx_types.h"
#include <string.h>
#include <limits.h>
#include <stdlib.h>
#include <libgen.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    // Usage: xxx-ext4 -[h,d] FILE
    if (argc < 3)
    {
        printf("Usage: xxx-ext4 -[h,d] FILE \n");
        return 1;
    }
    // only support regular file and dir
    int ret = 0;
    struct stat file_st = {};
    ret = lstat(argv[2], &file_st); // lstat don't reslove link
    if (ret != 0)
        return -1;
    if (S_ISLNK(file_st.st_mode))
        return -1;
    if (!S_ISREG(file_st.st_mode) && !S_ISDIR(file_st.st_mode))
        return -1;

    // get realpath
    char filepath[PATH_MAX];
    if (realpath(argv[2], filepath) == NULL)
        return 2;

    char filepath2[PATH_MAX];
    strncpy(filepath2, filepath, PATH_MAX);
    const char *dirpath = dirname(filepath2);

    if (strcmp("/", dirpath) == 0)
        return 3;

    // xxx-ext4 lib functions
    struct xxx_info info = {};
    ret = load_xxx_info(&info, filepath);

    printf("load_xxx_info ret: %d\n", ret);
    if (ret == 0)
    {
        printf("loaded \n");
    }
    else if (ret == -1)
    {
        deploy_xxx_subfs(&info, true);
        read_xxx_info(&info);
    }
    else
    {
        return -1;
    }


    if (strcmp(argv[1], "-h") == 0)
    {
        ret = hide_file(&info, filepath);
        printf("hide %d, %s \n", ret, filepath);
    }
    else if (strcmp(argv[1], "-d") == 0)
    {
        ret = show_file(&info, filepath);
        printf("show %d, %s \n", ret, filepath);
    }
    else
    {
        printf("invalid args\n");
    }
    free_xxx_info(&info);

    return 0;
}
